package com.haixiaoke.saas.lock.service.impl;

import java.time.*;
import java.util.Date;
import java.util.List;
import java.util.Objects;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.haixiaoke.saas.common.constant.DeviceLockConstants;
import com.haixiaoke.saas.common.core.domain.AjaxResult;
import com.haixiaoke.saas.common.enums.DefaultEnum;
import com.haixiaoke.saas.common.utils.DateUtils;
import com.haixiaoke.saas.lock.domain.DeviceLock;
import com.haixiaoke.saas.lock.domain.LockFace;
import com.haixiaoke.saas.lock.domain.LockPwd;
import com.haixiaoke.saas.lock.mapper.LockPwdMapper;
import com.haixiaoke.saas.lock.service.IDeviceLockService;
import com.haixiaoke.saas.lock.service.ILockFaceService;
import com.haixiaoke.saas.lock.service.ILockOperatingRecordService;
import com.haixiaoke.saas.lock.service.ILockPwdService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 锁密码授权Service业务层处理
 *
 * @author panda
 * @date 2025-04-02
 */
@Service
public class LockPwdServiceImpl implements ILockPwdService {
    @Autowired
    private LockPwdMapper lockPwdMapper;
    @Autowired
    private LockDevicesService lockDevicesService;
    @Autowired
    private IDeviceLockService deviceLockService;
    @Autowired
    private ILockFaceService lockFaceService;
    @Autowired
    private ILockOperatingRecordService lockOperatingRecordService;

    /**
     * 查询锁密码授权
     *
     * @param pwdId 锁密码授权主键
     * @return 锁密码授权
     */
    @Override
    public LockPwd selectLockPwdByPwdId(Long pwdId) {
        return lockPwdMapper.selectLockPwdByPwdId(pwdId);
    }

    /**
     * 查询锁密码授权列表
     *
     * @param lockPwd 锁密码授权
     * @return 锁密码授权
     */
    @Override
    public List<LockPwd> selectLockPwdList(LockPwd lockPwd) {
        return lockPwdMapper.selectLockPwdList(lockPwd);
    }

    /**
     * 新增锁密码授权
     *
     * @param lockPwd 锁密码授权
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult insertLockPwd(LockPwd lockPwd) {
        if (lockPwd.getLockId() == null) {
            return AjaxResult.error("请选择锁");
        }
        String password = null;
        if (StrUtil.isNotBlank(lockPwd.getIdentification())) {
            //随机生成密码
            password = RandomUtil.randomNumbers(6);
            lockPwd.setPassword(password);
        }
        if (StrUtil.isBlank(lockPwd.getPassword()) ||
                lockPwd.getPassword().length() < 6) {
            return AjaxResult.error("密码格式有误,请输入6位数字密码");
        }
        if (lockPwd.getUserId() != null) {
            LockFace face = lockFaceService.selectLockFaceByLockIdAndUserId(lockPwd.getLockId(), lockPwd.getUserId());
            if (ObjectUtil.isNotEmpty(face)) {
                lockPwd.setUserName(face.getUserName());
            }
        }
        DeviceLock lock = deviceLockService.selectDeviceLockByLockId(lockPwd.getLockId());
        if (ObjectUtil.isEmpty(lock)) {
            return AjaxResult.error("锁数据异常");
        }
        Date nowDate = DateUtils.getNowDate();
        LocalDate nowLocalDate = LocalDate.now();
        ZonedDateTime zonedDateTime = lockPwd.getAuthStartTime().toInstant().atZone(ZoneId.systemDefault());
        if (nowLocalDate.isAfter(zonedDateTime.toLocalDate())) {
            return AjaxResult.error("授权开始时间不可小于当前时间");
        }
        lockPwd.setCreateTime(nowDate);
        lockPwd.setIdentification(lockDevicesService.getIdentification());

        if (StrUtil.equals(DeviceLockConstants.AUTH_TIME_TYPE_LONG, lockPwd.getAuthTimeType())) {
            LocalDateTime startTime = zonedDateTime.toLocalDateTime();
            LocalDateTime endDateTime = startTime.plusYears(20)
                    .with(LocalTime.MAX); // 直接设置为当天的最后一刻
            lockPwd.setAuthEndTime(Date.from(endDateTime.atZone(ZoneId.systemDefault()).toInstant()));
        }
        int result = lockPwdMapper.insertLockPwd(lockPwd);
        if (result > 0) {
            lockDevicesService.createLockPwd(lockPwd.getAuthStartTime(), lockPwd.getAuthEndTime(),
                    lock.getLockMac(), lockPwd.getPassword(), lockPwd.getIdentification());

            // 新增锁操作记录
            lockOperatingRecordService.addLockOperatingRecord(lockPwd.getLockId(), lockPwd.getUserName(),
                    DeviceLockConstants.OPERATING_TYPE_ADD, "新增密码：编号" + lockPwd.getPwdId());
            return AjaxResult.success(password);
        }
        return AjaxResult.error();
    }

    /**
     * 批量删除锁密码授权
     *
     * @param pwdIds 需要删除的锁密码授权主键
     * @return 结果
     */
    @Override
    public int deleteLockPwdByPwdIds(Long[] pwdIds) {
        return lockPwdMapper.deleteLockPwdByPwdIds(pwdIds);
    }

    /**
     * 删除锁密码授权信息
     *
     * @param pwdId    锁密码授权主键
     * @param loginUserId
     * @return 结果
     */
    @Override
    @Transactional
    public AjaxResult deleteLockPwdByPwdId(Long pwdId, Long loginUserId) {
        LockPwd lockPwd = lockPwdMapper.selectLockPwdByPwdId(pwdId);
        if (ObjectUtil.isEmpty(lockPwd)) {
            return AjaxResult.error("锁密码不存在");
        }
        DeviceLock deviceLock = deviceLockService.selectDeviceLockByLockId(lockPwd.getLockId());
        if (ObjectUtil.isEmpty(deviceLock)) {
            return AjaxResult.error("锁不存在");
        }
        LockFace face;
        if (loginUserId == null) {
            face = lockFaceService.selectLockFaceByLockIdByMainAdmin(deviceLock.getLockId());
            if (ObjectUtil.isEmpty(face)) {
                return AjaxResult.error("主管理员数据异常");
            }
        } else {
            face = lockFaceService.selectLockFaceByLockIdAndUserId(deviceLock.getLockId(), loginUserId);
            if (StrUtil.equals(DeviceLockConstants.AUTH_ROLE_TYPE_ADMIN, face.getAuthRoleType()) &&
                    !Objects.equals(lockPwd.getUserId(), face.getUserId())) {
                return AjaxResult.error("管理员只能删除自己申请的密码");
            }
        }
        if (StrUtil.equals(DeviceLockConstants.LOCK_STATE_ENABLE, lockPwd.getPwdState())) {
            lockDevicesService.removeLockPwd(deviceLock.getLockMac(), lockPwd.getIdentification());
        }
        int result = lockPwdMapper.softDeleteLockPwdByPwdId(pwdId);
        if (result > 0) {
            // 新增锁操作记录
            lockOperatingRecordService.addLockOperatingRecord(lockPwd.getLockId(), face.getUserName(),
                    DeviceLockConstants.OPERATING_TYPE_DELETE, "删除密码：编号" + lockPwd.getPwdId());
        }
        return result > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    @Override
    public void removeLockPwd(DeviceLock lock, LockFace lockFace) {
        List<LockPwd> lockPwdList = lockPwdMapper.selectLockPwdByLockIdAndUserId(lockFace.getLockId(), lockFace.getUserId(), DeviceLockConstants.LOCK_STATE_ENABLE);
        if (CollectionUtil.isNotEmpty(lockPwdList)) {
            for (LockPwd lockPwd : lockPwdList) {
                lockDevicesService.removeLockPwd(lock.getLockMac(), lockPwd.getIdentification());
                lockPwd.setPwdState(DeviceLockConstants.LOCK_STATE_FORBIDDEN);
                lockPwd.setForbiddenUserId(lockFace.getForbiddenUserId());
            }
            lockPwdMapper.updateBatchLockPwd(lockPwdList);
        }
    }

    @Override
    public void createLockPwd(DeviceLock lock, LockFace lockFace) {
        List<LockPwd> lockPwdList = lockPwdMapper.selectLockPwdByLockIdAndUserId(lockFace.getLockId(), lockFace.getUserId(), DeviceLockConstants.LOCK_STATE_FORBIDDEN);
        if (CollectionUtil.isNotEmpty(lockPwdList)) {
            Date startTime = DateUtils.getNowDate();
            Date endTime = DateUtils.addYears(startTime, 10);
            for (LockPwd lockPwd : lockPwdList) {
                lockDevicesService.createLockPwd(startTime, endTime, lock.getLockMac(), lockPwd.getPassword(), lockPwd.getIdentification());
                lockPwd.setPwdState(DeviceLockConstants.LOCK_STATE_ENABLE);
            }
            lockPwdMapper.updateBatchLockPwd(lockPwdList);
        }
    }

    @Override
    public List<LockPwd> selectLockPwdByUserId(Long userId) {
        return lockPwdMapper.selectLockPwdByUserId(userId);
    }

    @Override
    public int softDeleteLockPwdByUserId(Long userId) {
        return lockPwdMapper.softDeleteLockPwdByUserId(userId);
    }

    @Override
    @Transactional
    public AjaxResult editPwdState(Long pwdId, Long loginUserId) {
        LockPwd lockPwd = lockPwdMapper.selectLockPwdByPwdId(pwdId);
        if (ObjectUtil.isEmpty(lockPwd)) {
            return AjaxResult.error("锁密码不存在");
        }
        if (lockPwd.getUserId() == null) {
            return AjaxResult.error("平台密码无权操作状态");
        }
        DeviceLock lock = deviceLockService.selectDeviceLockByLockId(lockPwd.getLockId());
        if (ObjectUtil.isEmpty(lock)) {
            return AjaxResult.error("锁不存在");
        }
        LockFace face = lockFaceService.selectLockFaceByLockIdAndUserId(lock.getLockId(), loginUserId);
        if (ObjectUtil.isEmpty(face)) {
            return AjaxResult.error("当前账号无权限该操作");
        }

        Date nowDate = DateUtils.getNowDate();
        if (StrUtil.equals(DeviceLockConstants.LOCK_STATE_ENABLE, lockPwd.getPwdState())) {
            if (StrUtil.equals(DeviceLockConstants.AUTH_ROLE_TYPE_ADMIN, face.getAuthRoleType()) &&
                    !Objects.equals(lockPwd.getUserId(), loginUserId)) {
                return AjaxResult.error("管理员无法干涉其他管理员申请的密码");
            }
            lockPwd.setPwdState(DeviceLockConstants.LOCK_STATE_FORBIDDEN);
            lockPwd.setForbiddenUserId(loginUserId);
            lockDevicesService.removeLockPwd(lock.getLockMac(), lockPwd.getIdentification());
        } else if (StrUtil.equals(DeviceLockConstants.LOCK_STATE_FORBIDDEN, lockPwd.getPwdState())) {
            if (lockPwd.getUserId() != null) {
                LockFace lockFace = lockFaceService.selectLockFaceByLockIdAndUserId(lock.getLockId(), lockPwd.getUserId());
                if (StrUtil.equals(DeviceLockConstants.LOCK_STATE_FORBIDDEN, lockFace.getFaceState())) {
                    return AjaxResult.error("该用户授权已被禁用,无法启用");
                }
            }
            //判断是否是主管理员禁用的
            LockFace forbiddenLockFace = lockFaceService.selectLockFaceByLockIdAndUserId(lockPwd.getLockId(), lockPwd.getForbiddenUserId());
            if (ObjectUtil.isNotEmpty(forbiddenLockFace) && !Objects.equals(face.getFaceId(), forbiddenLockFace.getFaceId()) &&
                    StrUtil.equals(DeviceLockConstants.AUTH_ROLE_TYPE_MAIN_ADMIN, forbiddenLockFace.getAuthRoleType())) {
                return AjaxResult.error("该密码被主管理员禁用,无法启用");
            }
            lockPwd.setPwdState(DeviceLockConstants.LOCK_STATE_ENABLE);
            lockPwd.setForbiddenUserId(null);
            lockDevicesService.createLockPwd(nowDate, DateUtils.addYears(nowDate, 10), lock.getLockMac(),
                    lockPwd.getPassword(), lockPwd.getIdentification());
        }
        lockPwd.setUpdateTime(nowDate);
        int result = lockPwdMapper.updateLockPwd(lockPwd);
        if (result > 0) {
            // 新增锁操作记录
            lockOperatingRecordService.addLockOperatingRecord(lockPwd.getLockId(), face.getUserName(),
                    DeviceLockConstants.OPERATING_TYPE_EDIT, face.getUserName() + DefaultEnum.getLabelByValue(lockPwd.getPwdState()) + "了" + lockPwd.getUserName() + "的授权");
        }
        return result > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    @Override
    @Transactional
    public AjaxResult manageEditPwdState(Long pwdId) {
        LockPwd lockPwd = lockPwdMapper.selectLockPwdByPwdId(pwdId);
        if (ObjectUtil.isEmpty(lockPwd)) {
            return AjaxResult.error("锁密码不存在");
        }
        DeviceLock lock = deviceLockService.selectDeviceLockByLockId(lockPwd.getLockId());
        if (ObjectUtil.isEmpty(lock)) {
            return AjaxResult.error("锁不存在");
        }

        Date nowDate = DateUtils.getNowDate();
        if (StrUtil.equals(DeviceLockConstants.LOCK_STATE_ENABLE, lockPwd.getPwdState())) {
            lockPwd.setPwdState(DeviceLockConstants.LOCK_STATE_FORBIDDEN);
            lockDevicesService.removeLockPwd(lock.getLockMac(), lockPwd.getIdentification());
        } else if (StrUtil.equals(DeviceLockConstants.LOCK_STATE_FORBIDDEN, lockPwd.getPwdState())) {
            if (lockPwd.getUserId() != null) {
                LockFace lockFace = lockFaceService.selectLockFaceByLockIdAndUserId(lock.getLockId(), lockPwd.getUserId());
                if (StrUtil.equals(DeviceLockConstants.LOCK_STATE_FORBIDDEN, lockFace.getFaceState())) {
                    return AjaxResult.error("该用户授权已被禁用,无法启用");
                }
            }
            lockPwd.setPwdState(DeviceLockConstants.LOCK_STATE_ENABLE);
            lockPwd.setForbiddenUserId(null);
            lockDevicesService.createLockPwd(nowDate, DateUtils.addYears(nowDate, 10), lock.getLockMac(),
                    lockPwd.getPassword(), lockPwd.getIdentification());
        }
        lockPwd.setUpdateTime(nowDate);
        int result = lockPwdMapper.updateLockPwd(lockPwd);
        if (result > 0) {
            // 新增锁操作记录
            lockOperatingRecordService.addLockOperatingRecord(lockPwd.getLockId(), "平台",
                    DeviceLockConstants.OPERATING_TYPE_EDIT, "平台" + DefaultEnum.getLabelByValue(lockPwd.getPwdState()) + "了" + lockPwd.getUserName() + "的授权");
        }
        return result > 0 ? AjaxResult.success() : AjaxResult.error();
    }

    @Override
    public int softDeleteLockPwdByLockId(Long lockId) {
        return lockPwdMapper.softDeleteLockPwdByLockId(lockId);
    }

    @Override
    public int softDeleteLockPwdByPwdId(Long pwdId) {
        return lockPwdMapper.softDeleteLockPwdByPwdId(pwdId);
    }

}
